import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "../store/index";
import NotFound from "../views/NotFound";
import Category from "../views/goods/Category";
import BestSell from "../views/goods/BestSell";
import Admin from "../views/roles/Admin";
import Login from "../views/Login";
import Home from "../views/Home";
Vue.use(VueRouter)
let Category_Rule = {path: '/category', name: 'category',hidden:true, component:Category }
let BestSell_Rule = {path: '/bestSell', name: 'bestSell', hidden:true,component: BestSell}
let Admin_Rule = {path: '/admin', name: 'admin',hidden:true, component:Admin}
const ruleMapping = {
    'category':Category_Rule,
    'bestSell': BestSell_Rule,
    'admin': Admin_Rule
}
const routes = [
    {
        path: '/login',
        name: 'login',
        hidden:true,
        component: Login
    },
    {
        path: '/',
        name: 'home',
        hidden:true,
        component: Home,
        redirect: '/category',
        children: [
            // {
            //     path: '/category',
            //     name: 'category',
            //     component: Category
            // },
            // {
            //     path: '/bestSell',
            //     name: 'bestSell',
            //     component:BestSell
            // },
            // {
            //     path: '/admin',
            //     name: 'admin',
            //     component:Admin
            // }
        ]
    },
    {
        path: '*',
        component:NotFound
    }

]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})
router.beforeEach((to, from, next) => {
    if (to.path == '/login') {
        next()
    } else {
        const token = localStorage.getItem('userToken')
        if (!token) {
            next('/login')
        } else {
            next()
        }
    }
})

// 动态路由
export function initRoutes() {
    // 获取所有写死的路由
    const currentRoutes = router.options.routes
    // 登录返回路由信息
    const rightList = store.state.user.userMsg.role
    rightList.forEach(item => {
        item.children.forEach(items => {
            const temp = ruleMapping[items.path]
            temp.meta = items.rights
            currentRoutes[1].children.push(temp)
        })
    })
    router.addRoutes(currentRoutes)
}

export default router
